<template>
	<view class="m-bg">
		<view class="m-top-bg">
			<image class="m-top-img" :src="mTopData.bgImg"></image>
			<view class="m-top-bg-mask"></view>
			<view class="m-top">
				<navigator url="/pages/plat_menu/index" open-type="switchTab" class="m-top-back"></navigator>
				<navigator url="/pages/shop_new/search/search" class="m-top-search"></navigator>
			</view>
		</view>
		<view class="m-card-wrap">
			<image :src="mTopData.logo" class="m-card-img"></image>
			<view class="m-card-title">{{ mTopData.name }}</view>
			<view class="m-score-wrap" v-if="mTopData.feature.length">
				<text v-if="mTopData.feature.length" v-for="(item, key) in mTopData.feature" :key="key">{{ item }}</text>
			</view>
			<view class="m-ticket-wrap" v-if="storeInfo.ticket_list.length">
				<text v-for="(item, index) in storeInfo.ticket_list" :key="index" @tap="clickCoupon($event)" :data-index="index">￥{{ item.discount }}</text>
			</view>
			<view class="m-discount-wrap" v-if="mTopData.coupon_list.length">
				<text v-for="(item, index) in mTopData.coupon_list" :key="index">{{ item.value }}</text>
			</view>
			<view class="m-notice">公告：{{ mTopData.store_tip }}</view>
		</view>

		<view class="m-nav-wrap">
			<view v-for="(item, index) in swichNavArr" :class="switchActive === index ? 'active' : ''" :key="index" @tap="swichNav(index)">{{ item }}</view>
		</view>

		<view class="m-nav-detail">
			<view v-if="currentTab == 0" class="m-scroll-wrap">
				<!-- 一级分类导航 -->
				<scroll-view scroll-y="true" scroll-top="0" class="m-scroll-nav">
					<view class="m-navlist-wrap">
						<view :class="'m-nav-one ' + (sort_index[0] == 'hot' ? 'active' : '')" v-if="storeInfo.cat_hot" @click.stop="clickOneNav($event)" data-index="hot">{{ storeInfo.cat_hot.name }}</view>
						<view :class="'m-nav-one ' + (sort_index[0] == 'discount' ? 'active' : '')" v-if="storeInfo.cat_discount" @click.stop="clickOneNav($event)" data-index="discount">{{ storeInfo.cat_discount.name }}</view>

						<view :class="'m-nav-one ' + (sort_index[0] == index1 ? 'active' : '')" v-for="(one, index1) in storeInfo.category_list" :key="index1" @click.stop="clickOneNav($event)" :data-index="index1">
							<text>{{ one.cat_name }}</text>
							<text class="num" :hidden="!selectType[one.cat_id]">{{ selectType[one.cat_id] }}</text>
							<!-- <view v-if="sort_index[0] == index1 && one.son_list" class="m-nav-two-wrap" v-for="(two, index2) in one.son_list" :key="index2" @click.stop="clickTwoNav($event)" :data-index="index2">
								<view :style="'color:' + (sort_index[1] == index2 && !two.son_list ? mobile_head_color : '')" :class="'m-nav-two ' + (sort_index[1] === index2 && !two.son_list ? 'active' : '')">
									<text>{{ two.cat_name }}</text>
									<text class='num'>12</text>
								</view>
							</view> -->
						</view>
					</view>
				</scroll-view>

				<!-- 商品列表 -->
				<scroll-view scroll-y="true" class="m-scroll-info" :scroll-top="scrollTop"  @scroll="scroll">
					<view>
						<view :id="'id_' + item.product_id" v-if="sortList.length > 0" v-for="item in sortList" :key="item.product_id" @tap="selectFormat($event)" :data-id="item.product_id"><GoodsItem klass="takeout-sub" :currency="currency" :refreshCount="refreshCount" :goods="item" @getGoods="getGoods"></GoodsItem></view>
					</view>
				</scroll-view>
			</view>

			<scroll-view v-if="currentTab == 1" :scroll-y="searchFixed" style="height:100%;padding-bottom: 20vw;" @scrolltolower="lowerComment">
				<view class="mark-box">
					<view class="score">
						<view :style="'color:' + mobile_head_color + ';'">{{ storeInfo.star }}</view>
						<view><lang keywords="商家评分"></lang></view>
					</view>
					<view class="star">
						<!-- <wux-rater :auto="false" slot="footer" :value="storeInfo.star" :font-size="16" disabled></wux-rater> -->
						<uni-rate :value="storeInfo.star" size="20" disabled="true"></uni-rate>
						<view>
							<lang keywords="店铺综合评分"></lang>
							<lang keywords="共X1人评价" :X1="storeInfo.reply_count" :needUpdate="true"></lang>
						</view>
					</view>
					<view class="percent" v-if="storeInfo.delivery || storeInfo.delivery_system">
						<view>{{ storeInfo.reply_deliver_score }}</view>
						<view><lang keywords="配送满意度"></lang></view>
					</view>
				</view>

				<view class="gap"></view>
				<view class="assess-box">
					<view class="assess-type">
						<view :class="'good ' + (tab === '' ? 'active' : '')" :style="'background:' + (tab === '' ? mobile_head_color : '')" @click.stop="commentTab($event)" data-type="">
							<lang keywords="全部"></lang>
							{{ comment.all_count }}
						</view>
						<view :class="'good ' + (tab === 'good' ? 'active' : '')" :style="'background:' + (tab === 'good' ? mobile_head_color : '')" @click.stop="commentTab($event)" data-type="good">
							<lang keywords="满意"></lang>
							{{ comment.good_count }}
						</view>
						<view :class="'good ' + (tab === 'wrong' ? 'active' : '')" :style="'background:' + (tab === 'wrong' ? mobile_head_color : '')" @click.stop="commentTab($event)" data-type="wrong">
							<lang keywords="不满意"></lang>
							{{ comment.wrong_count }}
						</view>
					</view>

					<view class="item border-b" v-for="(item, index) in comment.list" :key="index">
						<view class="avatar"><image :src="item.avatar" lazy-load="true"></image></view>
						<view class="content">
							<view class="mb3">
								<text>{{ item.nickname }}</text>
								<text class="date">{{ item.add_time }}</text>
							</view>
							<view class="score-box mb3">
								<lang keywords="评分"></lang>
								<!-- <wux-rater slot="footer" :auto="false" :value="item.score" :font-size="12" disabled></wux-rater> -->
								<uni-rate :value="item.score" size="16" disabled="true"></uni-rate>
								<block v-if="storeInfo.delivery || storeInfo.delivery_system"><lang keywords="配送X1星" :X1="item.deliver_score"></lang></block>
							</view>
							<view class="mb3">{{ item.comment }}</view>
							<view class="image-box clearfix mb3" hidden="true">
								<view class="img" v-for="(item, index2) in [1, 2, 3, 4, 5]" :key="index2"><image :src="requestDomain + 'static/new_shop/sn_detailgoods1.png'" mode="widthFix" lazy-load="true"></image></view>
							</view>
							<view class="score-box mb3" v-if="item.goods.length > 0">
								<text class="iconfont icon-dianzan"></text>
								<text class="goods" v-for="(goods, index2) in item.goods" :key="index2">{{ goods }}</text>
							</view>

							<view class="reply-box" :hidden="item.merchant_reply_content === ''">
								<image src="../../../static/images/sn_triangle.png" class="icon" mode="widthFix" lazy-load="true"></image>
								<view class="reply">
									<lang keywords="商家回复"></lang>
									<text>：{{ item.merchant_reply_content }}</text>
								</view>
							</view>
						</view>
					</view>

					<view style="text-align:center;padding: 30px 0;" v-if="comment && comment.list.length == 0"><lang keywords="暂无评价"></lang></view>
				</view>
			</scroll-view>

			<scroll-view v-if="currentTab == 2" :scroll-y="searchFixed" style="height:100%;padding-bottom: 20vw;">
				<view>
					<view class="gap"></view>
					<view class="line border-b" @tap="checkLocation">
						<view class="left">
							<text class="iconfont icon-dingwei2"></text>
							<text>{{ storeInfo.adress }}</text>
						</view>
						<view class="right"><text class="iconfont icon-jiantou"></text></view>
					</view>
					<view class="line border-b">
						<scroll-view scroll-x="true">
							<view class="shop-img clearfix"><image :src="item" mode="aspectFill" lazy-load="true" v-for="(item, index) in storeInfo.images" :key="index" @tap="previewImage($event)" :data-index="index" data-name="images"></image></view>
						</scroll-view>
					</view>
					<view class="line" @click.stop="clickShow($event)" data-name="showCallBox">
						<view class="left">
							<text class="iconfont icon-phone"></text>
							<lang keywords="店铺电话"></lang>
							<text>：{{ storeInfo.phone }}</text>
						</view>
						<view class="right"><text class="iconfont icon-jiantou"></text></view>
					</view>

					<view class="gap"></view>
					<!-- 直播 -->
					<view v-if="storeInfo.store_live_is_show" class="line border-b">
						<view class="left">
							<text class="iconfont icon-zhibo"></text>
							<lang keywords="店铺直播"></lang>
						</view>
					</view>
					<view v-if="storeInfo.store_live_is_show" class="line border-b">
						<scroll-view scroll-x="true">
							<view class="shop-img clearfix">
								<view class="video-container" v-for="(item, index) in storeInfo.store_live_urls" :key="index" @click.stop="clickShow($event)" :data-live_url="item.live_url" data-name="showVideo">
									<image :src="item.live_pic" mode="aspectFill" lazy-load="true" :data-index="index" data-name="images"></image>
									<view class="video-name">
										<image class="bo-fang" src="../../../static/images/bofang.png"></image>
										<text class="video-text">{{ item.live_cate }}</text>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>

					<view class="gap"></view>
					<view class="line border-b line-time">
						<view class="left">
							<text class="iconfont icon-time"></text>
							<lang keywords="营业时间"></lang>
							：
							<view class="time-wrapper" :style="'color:#' + shopBackgroundColor + ';'" @click.stop="clickShow($event)" data-name="showTime">
								<text class="current-time">{{ storeInfo.time }}</text>
								<text class="iconfont icon-sanjiaoB"></text>
								<view :class="'time-box time-width' + time_width" :hidden="!showTime">
									<view :style="item.current ? 'color:#' + shopBackgroundColor : ''" v-for="(item, week) in storeInfo.time_arr" :key="week">{{ item.week_show + ' ' + item.time_show }}</view>
								</view>
							</view>
						</view>
						<view class="right"></view>
					</view>
					<view class="line">
						<view class="left">
							<text class="iconfont icon-car"></text>
							<lang v-if="storeInfo.deliver_type == 2" keywords="配送方式：本店只支持门店自提"></lang>
							<block v-else>
								<lang keywords="配送方式"></lang>
								：
								<lang v-if="storeInfo.deliver_type == 0 || storeInfo.deliver_type == 3" class="mr5" keywords="平台配送"></lang>
								<lang v-if="storeInfo.delivery && (storeInfo.deliver_type == 1 || storeInfo.deliver_type == 4)" class="mr5" keywords="商家配送"></lang>
								<lang v-if="storeInfo.deliver_type == 2 || storeInfo.deliver_type == 3 || storeInfo.deliver_type == 4" class="mr5" keywords="门店自提"></lang>
								<lang v-if="storeInfo.deliver_type == 5" class="mr5" keywords="快递配送"></lang>
							</block>
						</view>
						<view class="right"></view>
					</view>

					<view class="line-wrapper" v-if="storeInfo.merchant_links && storeInfo.merchant_links.length > 0">
						<view class="gap"></view>
						<view class="line border-b" v-for="(item, index) in storeInfo.merchant_links" :key="index" @click.stop="goUrl($event)" :data-url="item.link" :data-title="item.title">
							<view class="left">
								<image class="mr5" style="height:16px;width:16px;position:relative;top:2px;" :src="item.icon" lazy-load="true"></image>
								<text>{{ item.title }}</text>
							</view>
							<view class="right"><text class="iconfont icon-jiantou"></text></view>
						</view>
					</view>

					<view class="line-wrapper">
						<view class="gap"></view>
						<view class="line border-b">
							<view class="left">
								<text class="iconfont icon-gonggao"></text>
								<lang keywords="店铺公告"></lang>
								：
								<text v-if="storeInfo.store_notice">{{ storeInfo.store_notice }}</text>
								<lang v-else keywords="无"></lang>
							</view>
							<view class="right"></view>
						</view>

						<view class="line sale border-b" v-for="(item, index) in storeInfo.coupon_list" :key="index">
							<text :class="'text-icon jian ' + 'bg-' + item.type">{{ discount_icon[item.type] }}</text>
							<text>{{ item.value }}</text>
						</view>
					</view>

					<view v-if="storeInfo.auth_files.length > 0">
						<view class="gap"></view>
						<view class="line border-b"><lang keywords="资质证照"></lang></view>
						<view class="line">
							<scroll-view scroll-x="true">
								<view class="shop-img clearfix"><image :src="item" mode="aspctFill" lazy-load="true" v-for="(item, index) in storeInfo.auth_files" :key="index" @tap="previewImage($event)" :data-index="index" data-name="auth_files"></image></view>
							</scroll-view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- <view class="m-fix-bottom">
			<view class="m-fix-bottom-tel" @click="callMerchant">联系商家</view>
			<view class="m-fix-bottom-txt">
				<span>免配送费 | 支持自取</span>
				<span class="m-fix-bottom-price">￥15起送</span>
			</view>
		</view> -->

		<!-- 购物车 -->
		<view id="shopcart"><shopcart :isHomePage="true" :currentTab="currentTab" :refreshCart="refreshCart" @getGoods="getGoods"></shopcart></view>
	

		<!-- 规格弹窗 -->
		<spec-mask :show="showSpecMask" :productId="specProductId" :refreshCount="refreshCount" @getGoods="getGoods"></spec-mask>

		<userinfo :options="user_options" @getUserscope="getUserInfo" @toLogin="getUserInfo"></userinfo>

		<navigator class="m-t-fix-car" url="/pages/shop_new/cart/cart"><image src="../take-out/imgs/car.png" mode=""></image></navigator>
	</view>
</template>

<script>
import uniRate from '../../../appComponent/uni/uni-rate/uni-rate.vue'
import common from '../../../utils/common.js'
import head from '../../../utils/customHead.js'
import count from '../component/count/count'
import shopcart from '../component/shopcart/shopcart'
import specMask from '../component/spec-mask/spec-mask'
import shop_common from '../../../utils/shop/common.js'
import GoodsItem from '../component/goodsItem/goodsItem.vue'
import shopCommon from '../../../utils/shop/addToCart.js'
var app = getApp()
var _this
var canSimpleScroll = true
var cansetHeaderFixed = true
var shareTxt1 = '推荐您一个店铺'
var shareTxt2 = '有人一起拼单吗？'
var roll_interval = ''
var phoneInfo = ''

export default {
	data() {
		return {
			scrollTop: 0,
			oldScrollTop:0,
			mPhone: '',
			switchActive: 0,
			swichNavArr: ['点菜', '评价', '商家'],
			mTopData: {},
			winHeight1: 1000, // 窗口高度
			currentTab: 0, // 预设当前项的值
			scrollLeft: 0, // tab标题的滚动条位置
			searchRect: '', // 搜索框节点信息
			searchFixed: false,
			tabHeaderRect: '', // tab标题节点信息
			tabHeaderFixed: false,
			scrollHeight: '',
			topContentRect: '', // 商品列表上面的广告或者新品推荐节点信息
			scrollY: false,
			typeTitleArr: '',
			showCart: false, // 显示购物车中的商品
			showDetail: false, // 显示更多优惠信息
			showCallBox: false, // 显示联系电话弹窗
			showThreeList: false, // 显示第三级菜单
			store_id: '', // 店铺id
			storeInfo: '', // 店铺的基本信息
			contentTop: 0, // 点击商品菜单时，显示对应的商品
			topList: '', // 商品列表标题的top值
			sort_id: '', // 三级菜单开启时候的分类的ID
			sortList: [], // 与sort_id对应的商品列表
			sort_name: '', // 与sort_id对应的商品列表标题
			sort_discount: 0, // 与sort_id对应的分类折扣
			sort_desc: '', //分类描述
			sort_index: [0, 0, 0], // 三级菜单选中的index值
			selectGoods: [], // 选中的商品列表
			selectType: {}, // 商品列表标题上的数字角标
			goodsNumList: {}, // 商品选中数量对象
			totalNum: 0, // 选中商品的总数
			selectAdd: false, // 是否选择了加价送
			goodsKeyList: {}, // 当前加入购物车的相同商品的数量
			goodsSpecList: {}, // 当前加入购物车的同一规格的商品数量
			shopFrontColor: 'ffffff',
			shopBackgroundColor: '113533',
			scrollDistance: 0,
			comment: '',
			tab: '',
			pageIndex: 1, // 评论分页
			pageLoading: false,
			pageScrollTop: 0,
			refresh: 0,
			discount_icon: {
				invoice: common.changeTxt('票'),
				discount: common.changeTxt('折'),
				isdiscountgoods: common.changeTxt('限'),
				isdiscountsort: common.changeTxt('折'),
				delivery: common.changeTxt('惠'),
				system_newuser: common.changeTxt('首'),
				system_minus: common.changeTxt('减'),
				newuser: common.changeTxt('首'),
				minus: common.changeTxt('减'),
				delivery_free: common.changeTxt('惠'),
				full_gift: common.changeTxt('满赠 ')
			},

			isShare: 0, // 0 表示拼单发起人， 1表示拼单被邀请人
			showShare: false, // 显示分享按钮
			showPoster: false, // 显示海报
			width: 0,
			height: 0,
			canSave: true,
			search_sortId: '', // 搜索页面传来的商品分类ID
			search_goodsId: '', // 搜索页面传来的商品ID
			posterUrl: '', // 海报绘制是否成功
			posterComplete: false, // 海报绘制过程是否完成
			timer: null, // 纠正顶部固定定位的问题
			showSpecMask: false, // 是否显示规格弹窗
			refresh: false, // true 表示页面需要刷新
			pageIsScroll: false, // 页面是否能滚动
			scrollTimer: null, // 商品滚动延迟
			navIdList: {},
			showHomeIcon: false, // 左上角是否显示外卖首页图标
			isNewHeader: true, // 是否支持自定义标题栏
			has_desc: false, // 商品是否有描述
			uid: '', // 用户唯一id
			age_status: 0, // 用户年龄是否通过限制 0通过 1未知需输入 2未不通过
			check_coupon: false, // 领取优惠券时检查登录
			showVideo: false, //是否显示直播视频
			showTime: false, // 是否显示营业时间弹窗
			time_width: 1, // 标记时间弹窗的宽度
			pace: 1, //滚动速度
			posLeft2: 0, //水平滚动方法三中left值
			marginLeft: 60, //水平滚动方法三中两条文本之间的间距
			no_roll: true, // 公告默认不滚动
			showDailyTip: false, // 是否显示店铺营业时间提示
			marquee2_margin: 60,
			marqueeDistance2: 0,
			marqueePace: 1, //滚动速度
			hidden: 'auto',
			booking_time: '',
			hasConfig: '',
			phoneInfo: '',
			mobile_head_color: '',
			shop_show_deliverymoney: '',
			activityImgH: '',
			navTop: '',
			show_age: false,
			needLogin: '',
			is_demo_domain: '',
			specProductId: '',
			winHeight2: '',
			requestDomain: '',
			noProduct: false,
			webShareTip: false, // h5分享弹窗提示
			config: '',

			user_options: {},
			refreshCart: false, // 通知购物车更新
			refreshCount: false, // 通知计数器更新
			sortNumList: {},
			currency: '¥',
			showDiscountCaculator: false, // 显示满减套餐弹窗
			discountInfo: {}, // 满减套餐信息
			orderStatus: 0, // 0表示正常下单，1表示拼单分袋
			redirectUrl: '',
			discountId: '0',
			liveUrl: '', //当前点击直播地址
			live_id: 0, //通过直播过来的直播ID
			activityShare: false // 是否是由店铺专题页分享进来的
		}
	},

	onShareAppMessage(res) {
		;(_this.showPoster = false), (_this.showShare = false)

		return {
			title: `${shareTxt1}    「 ${_this.storeInfo.name} 」`,
			path: `/pages/shop_new/shopDetail/shopDetail?store_id=${_this.store_id}&backgroundColor=${_this.shopBackgroundColor}&frontColor=${_this.shopFrontColor}`
		}
	},

	onUnload() {
		clearInterval(roll_interval)
		app.globalData.storeInfo = ''
		app.globalData.storeCart = ''
		uni.$off('getGoods', _this.getGoods)
	},

	onHide: function() {
		clearInterval(roll_interval)
		roll_interval = 0
		this.showSpecMask = false
	},

	onShow() {
		if (_this.length > _this.boxWidth && roll_interval == 0) {
			console.log('onshow是否重新滚动公告')
			run2()
		}

		// 判断页面信息是否需要刷新
		if (_this.refresh === true) {
			// 请求店铺数据
			_this.sort_id = ''
			getShopInfo()
			_this.refresh = false
		}

		// #ifdef H5
		if (_this.storeInfo) {
			_this.setWxShare()
		}
		// #endif

		var orderTogether = wx.getStorageSync('orderTogether')
		if (orderTogether && orderTogether.store_id == _this.store_id) {
			_this.orderStatus = 1
		} else {
			_this.orderStatus = 0
		}

		if (app.globalData.storeInfo) {
			_this.getGoods({ action: 'updateCart' })
			if (_this.storeInfo.openclassfyindex == 1) {
				getGoodsList(_this.sort_id, 'update')
			}
		}

		if (app.globalData.pinUrl && (!orderTogether || (orderTogether && orderTogether.store_id != _this.store_id))) {
			uni.navigateTo({
				url: app.globalData.pinUrl
			})
		}
	},

	onLoad: function(options) {
		_this = this
		console.log('店铺详情页初始化', options)
		wx.setNavigationBarTitle({
			title: common.changeTxt('店铺详情')
		})
		wx.showLoading({
			title: common.changeTxt('加载中')
		})
		shareTxt1 = common.changeTxt(shareTxt1)
		shareTxt2 = common.changeTxt(shareTxt2)
		if (options.redirect) {
			app.globalData.pinUrl = decodeURIComponent(options.redirect)
			console.log('店铺详情页初始化, 需要跳转拼单', app.globalData.pinUrl)
		}

		if (options.share) {
			_this.activityShare = options.share
		}

		//通过直播到的店铺详情页
		if (options.live_id) {
			_this.live_id = options.live_id
		}

		//网页码转小程序码打开
		if (options.q) {
			options.q = decodeURIComponent(options.q)
			options.store_id = common.getUrlParam(options.q, 'store_id')
			if (!options.store_id) {
				options.store_id = common.getUrlParam(options.q, 'shop-id')
			}
			options.page_from = common.getUrlParam(options.q, 'page_from')
		}

		// 是否是识别二维码打开
		if (options.scene) {
			var scene = decodeURIComponent(options.scene)
			console.log('scene is ', scene)
			var arrPara = scene.split('&')
			var arr = []

			for (var i in arrPara) {
				arr = arrPara[i].split('=')

				_this[arr[0]] = arr[1]
			}
		} else if (options.store_id) {
			_this.store_id = options.store_id
		}

		var pages = getCurrentPages()

		if (pages.length == 1) {
			_this.showHomeIcon = true
		}

		if (options.frontColor && options.backgroundColor) {
			_this.shopFrontColor = options.frontColor
			_this.shopBackgroundColor = options.backgroundColor

			uni.setNavigationBarColor({
				frontColor: '#' + _this.shopFrontColor,
				backgroundColor: '#' + _this.shopBackgroundColor
			})
		}

		if (options.sort_id && options.goods_id) {
			_this.search_sortId = options.sort_id
			_this.search_goodsId = options.goods_id
			// 43 85
			// getGoodsList(options.sort_id);
		}

		if (app.globalData.is_login) {
			app.globalData.storeInfo = { store_id: _this.store_id }
			shopCommon.initCart().then(function(data) {
				if (data) {
					_this.selectType = data.sort_num
				} else {
					_this.selectType = {}
				}
				_this.getGoods({ action: 'updateCart' })
			})
		}

		// 商品活动专题图片高度 头部高度
		phoneInfo = wx.getSystemInfoSync()

		_this.phoneInfo = phoneInfo
		console.log('设备信息99999999999', phoneInfo)

		_this.videoH = ((phoneInfo.windowWidth * 0.92) / 4) * 3
		_this.activityImgH = ((phoneInfo.windowWidth - 20) * 176) / 686
		_this.requestDomain = common.requestDomain
		common.setMainColor(
			_this,
			function(config) {
				_this.shop_show_deliverymoney = config.config.shop_show_delivermoney ? config.config.shop_show_delivermoney : true
				// 请求店铺数据
				getShopInfo()
			},
			false
		)

		common.changeCurrency(_this)

		// 判断是否与小区ID绑定
		if (typeof options.village_id != 'undefined') {
			app.globalData.shopVilliageBind[_this.store_id] = options.village_id
		}

		setTimeout(() => {
			this.clickOneNav()
		}, 100)
	},
	components: {
		count,
		shopcart,
		specMask,
		uniRate,
		GoodsItem
	},
	methods: {
		scroll (e) {
			console.log('oldScrollTop')
			this.oldScrollTop = e.detail.scrollTop
		},
		callMerchant() {
			let _phoneNumber = this.mPhone
			console.log(_phoneNumber)
			if (_phoneNumber) {
				uni.makePhoneCall({
					phoneNumber: _phoneNumber
				})
			}
		},
		backtoHome() {
			uni.switchTab({
				url: '/pages/plat_menu/index'
			})
		},
		goLive(live_id) {
			if (!app.globalData.is_login) {
				_this.user_options = {
					toLogin: true,
					showWebMask: true
				}
			} else {
				uni.redirectTo({
					url: '../../live_and_video/live/viewer/main_page?live_id=' + live_id
				})
			}
		},
		getDiscountList(id) {
			let discount_id = id ? id : '0'
			if (id != '0') {
				_this.discountId = discount_id
			}
			common.post(
				'Shop_new&a=full_reduction',
				{ store_id: _this.store_id, discount_id: discount_id },
				data => {
					console.log('满减神器组合列表', data)
					if (data) {
						_this.discountInfo = data
						if (_this.discountId == '0' && data.discount_list && data.discount_list.length > 0) {
							_this.discountId = data.discount_list[0].id
						}
					}
				},
				_this,
				err => {}
			)
		},
		buyDicsountGoods(id) {
			if (!app.globalData.is_login) {
				_this.user_options = {
					toLogin: true,
					showWebMask: true
				}
			} else {
				common.post('Cart&a=addFullReduce', { full_reduce_goods_id: id, store_id: _this.store_id }, data => {
					shopCommon.initCart().then(function() {
						_this.getGoods({ action: 'updateCart' })
						_this.showDiscountCaculator = false
						wx.navigateTo({
							url: '/pages/shop_new/confirmOrder/newCart?store_id=' + _this.store_id
						})
					})
				})
			}
		},
		getUserInfo(e) {},
		// 收藏店铺
		markShop() {
			if (!app.globalData.is_login) {
				_this.user_options = {
					toLogin: true,
					showWebMask: true
				}
			} else {
				common.post('My&a=do_collect', { type: 'shop', collect_id: _this.store_id, noTip: true }, function(data) {
					console.log('收藏接口', data)
					if (_this.storeInfo.is_collect == 1) {
						_this.storeInfo.is_collect = 0
					} else {
						_this.storeInfo.is_collect = 1
					}
					uni.showToast({
						title: data
					})
				})
			}
		},
		setWxShare() {
			let pageLink = `${common.requestDomain}packapp/${common.wxapp_type}/pages/shop_new/shopDetail/shopDetail?store_id=${_this.store_id}&backgroundColor=${_this.shopBackgroundColor}&frontColor=${_this.shopFrontColor}`
			pageLink = common.addShareParam(pageLink)
			let shareWxLink = pageLink
			var shareData = {
				title: this.storeInfo.share_title,
				desc: this.storeInfo.txt_info,
				sendFriendLink: shareWxLink,
				share_img: this.storeInfo.image
			}
			common.setWxShare(shareData)
		},
		//回到顶部
		goTop() {
			_this.pageScrollTop = 0
			_this.navTop = 0
			_this.contentTop = 0
		},

		pageScroll(e) {
			var scrollTop = e.detail.scrollTop
			_this.scrollTop = scrollTop
			if (_this.searchRect.top < 0 || _this.tabHeaderRect.top < 0) {
				getNodeInfo('#search', 'searchRect') // 搜索框
				getNodeInfo('#tabHeader', 'tabHeaderRect') // tab头部
			}
			_this.isFixed(e.detail.scrollTop)
			_this.timer = setTimeout(() => {
				wx.createSelectorQuery()
					.select('#pageScroll')
					.fields(
						{
							scrollOffset: true
						},
						function(res) {
							if (res) {
								_this.isFixed(res.scrollTo)
							}
						}
					)
					.exec()
			}, 500)
		},

		isFixed(scrollTop) {
			// 搜索框定位
			if (scrollTop >= _this.searchRect.top && !_this.searchFixed) {
				_this.searchFixed = 'position:fixed;top:0;left:0;right:0;z-index:99;background:#' + _this.shopBackgroundColor
			} else if (scrollTop < _this.searchRect.top && _this.searchFixed) {
				_this.searchFixed = ''
			}

			// tab标题固定
			if (scrollTop >= _this.tabHeaderRect.top - 55 && !_this.tabHeaderFixed) {
				_this.tabHeaderFixed = 'position:fixed;top:55px;left:0;right:0;z-index:99;'
			} else if (scrollTop < _this.tabHeaderRect.top - 55 && _this.tabHeaderFixed) {
				_this.tabHeaderFixed = ''
			}
			// 商品列表可滑动
			if (scrollTop >= _this.scrollDistance - 15) {
				_this.pageScrollTop = _this.scrollDistance
				_this.scrollY = true
			} else if (scrollTop < _this.scrollDistance - 15 && _this.scrollY) {
				_this.pageScrollTop = scrollTop
				_this.scrollY = false
			}
		},

		goodsScroll(e) {
			console.log('zyl scroll', e.detail.scrollTop)
			// _this.contentTop = e.detail.scrollTop;
			var scrollY = _this.scrollTop >= _this.scrollDistance - 30
			if (_this.scrollY != scrollY) {
				_this.scrollY = scrollY
			}
		},
		// 点击标题切换当前页时改变样式
		swichNav: function(num) {
			this.switchActive = num
			if (this.currentTab == num) {
				return false
			} else {
				this.currentTab = num
			}

			if (num == 1 && !_this.comment.list) {
				getComment()
			}
		},

		// 点击店铺头像
		goUrl(e) {
			var url = e.currentTarget.dataset.url
			var tag = e.currentTarget.dataset.tag
			var title = e.currentTarget.dataset.title

			if (url != '') {
				if (tag) {
					common.parseUrl(url, 'shop', false, '')
				} else if (title) {
					common.parseUrl(url, '', false, title)
				} else {
					common.parseUrl(url, '', false, common.changeTxt('在线客服'))

					_this.showCallBox = false
				}
			}
		},

		// 拼单按钮
		orderTogether() {
			if (_this.storeInfo.is_close == 1) {
				_this.showDailyTip = true
				return
			}
			if (!app.globalData.is_login) {
				_this.user_options = {
					toLogin: true,
					showWebMask: true
				}
				return
			}
			let orderTogether = uni.getStorageSync('orderTogether')
			if (orderTogether && orderTogether.store_id != _this.store_id) {
				uni.removeStorageSync('orderTogether')
			}
			wx.navigateTo({
				url: `/pages/shop_new/orderTogether/orderTogether?store_id=${_this.storeInfo.store_id}`
			})
		},

		// 打开弹窗
		clickShow(e) {
			console.log('e.currentTarget.dataset.name', e.currentTarget.dataset.name)
			console.log('_this.posterUrl', _this.posterUrl)
			if ((e.currentTarget.dataset.name == 'showPoster' && _this.posterUrl === true) || e.currentTarget.dataset.name != 'showPoster') {
				if (!_this.showTime && e.currentTarget.dataset.name == 'showTime') {
					_this.showTime = true
				} else if (e.currentTarget.dataset.name == 'showShare') {
					// #ifdef H5
					if (common.$checkPlat.checkWeixin()) {
						_this.webShareTip = true
					} else {
						uni.showToast({
							icon: 'none',
							title: common.changeTxt('当前环境不支持分享')
						})
					}
					// #endif

					// #ifdef MP-ALIPAY || MP-WEIXIN
					_this[e.currentTarget.dataset.name] = true
					// #endif
				} else {
					_this[e.currentTarget.dataset.name] = true
					_this.showTime = false
					if (e.currentTarget.dataset.live_url) {
						// 直播
						this.liveUrl = e.currentTarget.dataset.live_url
						console.log(this.liveUrl)
					}
				}
			} else {
				wx.showToast({
					title: common.changeTxt('海报还未完成，请稍后再试！'),
					icon: 'none'
				})

				if (_this.posterUrl === false) {
					drowPoster()
				}
			}
		},

		// 关闭弹窗
		closeMask(e) {
			var name = e.currentTarget.dataset.name
			_this[name] = false
		},

		// 打开地图查看位置
		checkLocation() {
			// 百度经纬度转为腾讯经纬度
			baiduToTengxun()
		},

		// 拨打电话
		callPhone(e) {
			wx.makePhoneCall({
				phoneNumber: e.currentTarget.dataset.phone
			})

			_this.showCallBox = false
		},

		// 点击跳转到店铺商品搜素页
		goGoodSearch() {
			if (_this.showDetail) {
				_this.showDetail = false
			}

			wx.navigateTo({
				url: `/pages/shop_new/goodsSearch/goodsSearch?backgroundColor=${_this.shopBackgroundColor}&frontColor=${_this.shopFrontColor}&store_id=${_this.store_id}`
			})
		},

		// 扫一扫按钮
		goGoodQrcode() {
			// #ifdef H5
			if (common.$checkPlat.checkWeixin()) {
				common.jweixin.scanQRCode({
					needResult: 1,
					scanType: ['barCode'],
					success: res => {
						console.log('扫码成功', res)
						let barcode = res.resultStr.split(',')
						barcodeSearch(barcode[1])
					},
					fail: res => {
						console.log('扫码失败', res)
						if (res.errMsg != 'scanCode:fail' && res.errMsg != 'scanCode:fail cancel') {
							wx.showModal({
								title: common.changeTxt('错误提示'),
								content: res.errMsg,
								showCancel: false
							})
						}
					}
				})
			} else {
				uni.showToast({
					title: common.changeTxt('当前环境不支持扫码'),
					icon: 'none',
					duration: 2000
				})
			}

			// #endif

			// #ifdef MP-ALIPAY || MP-WEIXIN
			wx.scanCode({
				success: res => {
					wx.vibrateLong()
					console.log(res.result)
					barcodeSearch(res.result)
				},
				fail: res => {
					wx.vibrateLong()
					if (res.errMsg != 'scanCode:fail' && res.errMsg != 'scanCode:fail cancel') {
						wx.showModal({
							title: common.changeTxt('错误提示'),
							content: res.errMsg,
							showCancel: false
						})
					}
				}
			})
			// #endif
		},

		// 图片预览
		previewImage(e) {
			var index = e.currentTarget.dataset.index
			var name = e.currentTarget.dataset.name
			wx.previewImage({
				current: _this.storeInfo[name][index],
				// 当前显示图片的http链接
				urls: _this.storeInfo[name] // 需要预览的图片http链接列表
			})
		},

		// 未开启三级菜单：点击商品菜单
		clickNav(e) {
			var index = e.currentTarget.dataset.index

			if (!_this.scrollY) {
				_this.scrollY = true
				_this.pageScrollTop = _this.scrollDistance
			}

			_this.navIdList = {
				[_this.storeInfo.product_list[index].cat_id]: true
			}

			_this.contentTop = _this.typeTitleArr[index].top - _this.typeTitleArr[0].top
			_this.clickTitle = true
		},

		// 未开启三级菜单：滚动商品列表
		simpleScrollContent(e) {
			if (_this.clickTitle == true) {
				_this.clickTitle = false
				return
			} else {
				if (canSimpleScroll == false) {
					return
				}

				canSimpleScroll = false
				var scrollTop = e.detail.scrollTop
				var index = 0

				if (_this.topList[_this.topList.length - 1] != e.detail.scrollHeight) {
					_this.topList = _this.topList.concat(e.detail.scrollHeight)
				}

				for (var i = 0; i < _this.topList.length; i++) {
					if (scrollTop < _this.topList[i + 1]) {
						index = i
						break
					}
				}

				_this.navIdList = {
					[_this.storeInfo.product_list[index].cat_id]: true
				}

				_this.scrollTimer = setTimeout(() => {
					canSimpleScroll = true
				}, 50)
			}
		},

		// 开启三级菜单：点击第一次
		clickOneNav(e) {
			console.log('mScrollTop')
			this.scrollTop = this.oldScrollTop
			this.$nextTick(() =>{
				this.scrollTop = 0
			});
			
			var index1 = e ? e.currentTarget.dataset.index : 0
			if (_this.sort_index[0] === index1) {
				_this.sort_index = [index1, '', '']
				return
			}

			if (!_this.scrollY) {
				_this.scrollY = true
				_this.pageScrollTop = _this.scrollDistance
			}

			var sort_name = ''
			var sortList = _this.sortList
			var sort_discount = 0
			var sort_index = [index1, '', '']
			var sort_desc = ''

			if (index1 === 'hot') {
				sort_name = _this.storeInfo.cat_hot.name
				sortList = _this.storeInfo.cat_hot.good_list
				sort_desc = _this.storeInfo.cat_hot.desc
				_this.sort_id = ''
			} else if (index1 === 'discount') {
				sort_name = _this.storeInfo.cat_discount.name
				sortList = _this.storeInfo.cat_discount.good_list
				sort_desc = _this.storeInfo.cat_discount.desc
				_this.sort_id = ''
			} else {
				var category_list = _this.storeInfo.category_list
				sort_name = _this.sort_name

				var sortItem = ''
				if (!category_list[index1].son_list) {
					sortItem = category_list[index1]
				} else if (!category_list[index1].son_list[0].son_list) {
					sort_index = [index1, 0, '']
					sortItem = category_list[index1].son_list[0]
				} else {
					sort_index = [index1, 0, 0]
					sortItem = category_list[index1].son_list[0].son_list[0]
				}
				sort_name = sortItem.sort_name
				sort_discount = sortItem.sort_discount / 10
				getGoodsList(sortItem.sort_id)
			}

			_this.sort_index = sort_index
			_this.sort_name = sort_name
			_this.sort_discount = sort_discount
			_this.sortList = sortList
			_this.sort_desc = sort_desc
			_this.contentTop = 0
		},

		// 开启三级菜单：点击第二次
		clickTwoNav(e) {
			if (_this.sort_index[1] === e.currentTarget.dataset.index) {
				_this.sort_index = [_this.sort_index[0], '', '']
				return
			} else {
				var index2 = e.currentTarget.dataset.index
			}
			var category_list = _this.storeInfo.category_list
			var sort_name = _this.sort_name
			var sort_index = _this.sort_index
			var sort_discount = 0
			sort_index[1] = index2
			sort_index[2] = ''
			var sortItem = ''

			if (!category_list[sort_index[0]].son_list[index2].son_list) {
				sortItem = category_list[sort_index[0]].son_list[index2]
			} else {
				sortItem = category_list[sort_index[0]].son_list[index2].son_list[0]
			}
			var sort_id = sortItem.sort_id
			sort_name = sortItem.sort_name
			sort_discount = sortItem.sort_discount / 10
			getGoodsList(sort_id)
			_this.sort_index = sort_index
			_this.sort_name = sort_name
			_this.sort_discount = sort_discount
			_this.$forceUpdate()
		},

		// 开启三级菜单：点击第三次
		clickThreeNav(e) {
			var index3 = e.currentTarget.dataset.index
			var category_list = _this.storeInfo.category_list
			var sort_index = _this.sort_index
			sort_index[2] = index3
			var sort_id = category_list[sort_index[0]].son_list[sort_index[1]].son_list[index3].sort_id
			var sort_name = category_list[sort_index[0]].son_list[sort_index[1]].son_list[index3].sort_name
			var sort_discount = category_list[sort_index[0]].son_list[sort_index[1]].son_list[index3].sort_discount / 10
			getGoodsList(sort_id)

			_this.sort_index = sort_index
			_this.sort_name = sort_name
			_this.sort_discount = sort_discount
		},

		openBuySort() {
			if (!_this.scrollY) {
				_this.pageScrollTop = _this.scrollDistance
				_this.scrollY = true
			}
			let buyId = app.globalData.storeCart.required_sort.sort_id
			if (_this.storeInfo.openclassfyindex == 1) {
				let one = 0
				let two = 0
				let three = 0
				let sortItem = {}
				outer: for (let i = 0; i < _this.storeInfo.category_list.length; i++) {
					let oneItem = _this.storeInfo.category_list[i]
					if (oneItem.son_list) {
						for (let j = 0; j < oneItem.son_list.length; j++) {
							let twoItem = oneItem.son_list[j]
							if (twoItem.son_list) {
								for (let k = 0; k < twoItem.son_list.length; k++) {
									let threeItem = twoItem.son_list[k]
									if (threeItem.cat_id == buyId || twoItem.cat_id == buyId || oneItem.cat_id == buyId) {
										console.log('必选分类 三级分类', threeItem)
										one = i
										two = j
										three = k
										sortItem = threeItem
										break outer
									}
								}
							} else if (twoItem.cat_id == buyId || oneItem.cat_id == buyId) {
								console.log('必选分类 二级分类', twoItem)
								one = i
								two = j
								sortItem = twoItem
								break outer
							}
						}
					} else if (oneItem.cat_id == buyId) {
						console.log('必选分类 一级分类', oneItem)
						one = i
						sortItem = oneItem
						break outer
					}
				}
				getGoodsList(sortItem.cat_id)
				_this.sort_index = [one, two, three]
				_this.sort_name = sortItem.sort_name
				_this.sort_discount = sortItem.sort_discount / 10
				console.log('三级分类index', one, two, three)
			} else {
				let index = 0
				for (let i = 0; i < _this.storeInfo.product_list.length; i++) {
					if (_this.storeInfo.product_list[i].cat_id == buyId) {
						index = i
						break
					}
				}

				_this.navIdList = {
					[_this.storeInfo.product_list[index].cat_id]: true
				}

				_this.contentTop = _this.typeTitleArr[index].top - _this.typeTitleArr[0].top

				_this.clickTitle = true
			}
		},

		// 点击商品加减按钮
		getGoods(e) {
			console.log('店铺详情页', e, _this.showSpecMask)

			// 登录
			if (e.action == 'login') {
				_this.user_options = {
					toLogin: true,
					showWebMask: true
				}
				return
			}

			// 必选分类提示
			if (e.action == 'mustBuySort') {
				_this.openBuySort()
				return
			}

			// 打开规格商品弹窗
			if (e.action == 'openSpecMask') {
				_this.showSpecMask = true
				_this.specProductId = e.goodsId
				return
			}

			// 关闭规格商品弹窗
			if (e.action == 'closeSpecMask') {
				_this.showSpecMask = false
				return
			}

			// 更新购物车
			if (e.action == 'updateCart') {
				_this.$nextTick(function() {
					_this.refreshCart = true
					_this.refreshCount = true
				})
				_this.selectType = app.globalData.storeCart ? app.globalData.storeCart.sort_num : {}
				return
			}

			// 更新购物车结束
			if (e.action == 'updateCartOver') {
				_this.$nextTick(function() {
					_this.refreshCart = false
					_this.refreshCount = false
				})
				return
			}

			// 清空购物车
			if (e.action == 'clearCart') {
				_this.selectType = {}
				_this.$nextTick(function() {
					_this.refreshCount = true
				})
				return
			}
		},

		// 打开商品详情
		selectFormat(e) {
			var product_id = ''

			if (e.product_id) {
				product_id = e.product_id
			} else {
				product_id = e.currentTarget.dataset.id
			}

			wx.navigateTo({
				url: `/pages/shop_new/goodsDetail/goodsDetail?store_id=${_this.store_id}&&product_id=${product_id}&&backgroundColor=${_this.shopBackgroundColor}&frontColor=${_this.shopFrontColor}`
			})
		},

		// 切换评价分类
		commentTab(e) {
			var tab = e.currentTarget.dataset.type
			console.log(tab)
			// 修复bug tab = "" 取出来在小程序里面会变成true
			if (tab === true) {
				tab = ''
			}
			_this.tab = tab
			_this.pageIndex = 1

			getComment()
		},

		// 评价分页
		lowerComment() {
			if (_this.pageLoading) {
				getComment()
			}
		},

		// 跳转到活动商品页
		gotoActivity() {
			wx.navigateTo({
				url: `/pages/shop_new/goodsActivity/goodsActivity?store_id=${_this.store_id}&frontColor=${_this.shopFrontColor}&backgroundColor=${_this.shopBackgroundColor}`
			})
		},

		// 点击领取优惠券
		clickCoupon(e) {
			var index = e.currentTarget.dataset.index
			var ticket = wx.getStorageSync('ticket')

			if (ticket) {
				_this.isCanGetCoupon(index)
			} else {
				_this.needLogin = true
				_this.check_coupon = true
				_this.ticketIndex = index
			}
		},

		isCanGetCoupon(index) {
			if (_this.storeInfo.ticket_list[index].active == true) {
				common.getTxtKey('已经领取过了~').then(
					key => {
						wx.showToast({
							title: key,
							icon: 'none'
						})
					},
					() => {}
				)
			} else {
				_this.storeInfo.ticket_list[index].active = true

				getCoupon(_this.storeInfo.ticket_list[index].coupon_id)
			}
		},

		// 保存图片
		savePoster() {
			wx.getSetting({
				success: res => {
					//不存在相册授权
					if (res.authSetting['scope.writePhotosAlbum'] == undefined || res.authSetting['scope.writePhotosAlbum'] == true) {
						saveImg()
					} else if (res.authSetting['scope.writePhotosAlbum'] == false) {
						_this.canSave = false
					}
				}
			})
		},

		// 打开授权设置
		handleSetting(e) {
			if (e.detail.authSetting['scope.writePhotosAlbum'] == true) {
				saveImg()
				_this.canSave = true
			}
		},

		// 播放视频报错
		videoErrorCallback(e) {
			console.log('333333333333333', e)
		},

		//防止事件冒泡，不能删
		clickPrevent() {}
	}
}
// 拼单结算获取规格商品的规格属性
const getSpecParam = specGoods => {
	var spec = []
	var prop = []

	if (specGoods.spec_list && specGoods.spec_list.length > 0) {
		spec = specGoods.spec_list.map(i => {
			var spec_item = {
				type: 'spec',
				name: i.name,
				spec_id: i.sid,
				id: i.id_
			}
			return spec_item
		})
	}

	if (specGoods.prop_list && specGoods.prop_list.length > 0) {
		prop = specGoods.prop_list.map(i => {
			var prop_item = {
				type: 'properties',
				data: []
			}

			for (var j = 0; j < i.val_status.length; j++) {
				if (i.val_status[j][1] === 0) {
					var obj = {
						id: j,
						list_id: i.id_,
						name: i.val_status[j][0]
					}
					prop_item.data = prop_item.data.concat(obj)
				}
			}

			return prop_item
		})
	}

	return spec.concat(prop)
}

// 判断年龄和关店
const isCanBuy = () => {
	return new Promise((resolve, reject) => {
		if (_this.storeInfo.is_close == 1) {
			_this.showDailyTip = true
			return
		}

		if (_this.storeInfo.check_age_object.check_age) {
			var ticket = wx.getStorageSync('ticket')

			if (!ticket || !app.globalData.userInfo) {
				_this.needLogin = true

				return
			} else {
				var user_age = app.globalData.userInfo.age * 1
				var limit_age = _this.storeInfo.check_age_object.age_limit_buy * 1 // 生日未知

				if (user_age <= 0) {
					_this.age_status = 1
					_this.show_age = true

					return
				}
				// 生日小于限制年龄
				if (user_age < limit_age) {
					_this.age_status = 2
					_this.show_age = true

					return
				}
				resolve()
			}
		}

		resolve()
	})
}
// 获取店铺信息
const getShopInfo = () => {
	var param = {
		store_id: _this.store_id,
		lng: '',
		lat: ''
	}
	var delivery_address = app.globalData.delivery_address

	if (delivery_address) {
		param.lng = delivery_address.lng
		param.lat = delivery_address.lat
	} else {
		//首页带来的定位
		var userLocation = wx.getStorageSync('userLocation')
		if (userLocation) {
			param.lng = userLocation.lng
			param.lat = userLocation.lat
			param.locaitonType = userLocation.type
		}
	}

	common.post('Shop_new&a=ajax_shop', param, data => {
		if (data) {
			let mTopData = {
				name: data.name,
				bgImg: data.images[0],
				logo: data.image,
				store_tip: data.txt_info,
				coupon_list: data.coupon_list,
				feature: data.feature
			}
			_this.mTopData = mTopData
			_this.mPhone = data.phone
			if ((data.product_list && data.product_list.length == 0 && data.openclassfyindex != 1) || (data.category_list && data.category_list.length == 0)) {
				_this.noProduct = true
				wx.showModal({
					title: common.changeTxt('提示'),
					content: common.changeTxt('该店铺正在建设中，暂无商品'),
					showCancel: false,
					confirmText: common.changeTxt('好的')
				})
			}

			var coupon1 = data.coupon_list.filter(item => item.type != 'invoice')
			var coupon2 = data.coupon_list.filter(item => item.type == 'invoice')
			data.coupon_list = coupon1.concat(coupon2)

			if (data.shop_showcase.good_count > 0) {
				data.shop_showcase.good_list = isSoldOut(data.shop_showcase.good_list)
			}

			if (data.cat_hot) {
				data.cat_hot.good_list = isSoldOut(data.cat_hot.good_list)
			}

			if (data.cat_discount) {
				data.cat_discount.good_list = isSoldOut(data.cat_discount.good_list)
			}

			if (data.product_list) {
				if (data.cat_discount) {
					var obj = {
						cat_name: data.cat_discount.name,
						sort_discount: 0,
						product_list: data.cat_discount.good_list,
						cat_id: 'discount',
						desc: data.cat_discount.desc
					}
					data.product_list.unshift(obj)
				}

				if (data.cat_hot) {
					var obj = {
						cat_name: data.cat_hot.name,
						sort_discount: 0,
						product_list: data.cat_hot.good_list,
						cat_id: 'hot',
						desc: data.cat_hot.desc
					}
					data.product_list.unshift(obj)
				}

				data.product_list = data.product_list.map((item, index) => {
					item.active = index === 0
					if (item.active) {
						_this.navIdList[item.cat_id] = item.active
					}
					item.product_list = isSoldOut(item.product_list)
					return item
				})
			}
			// 初次加载时获取的sort_id
			var sort_name = ''
			var sort_id = ''
			var sort_discount = 0
			var sortList = []
			var sort_index = [0, 0, 0]
			var sort_desc = ''
			// 开启了多级分类

			if (data.openclassfyindex == 1) {
				if (_this.search_sortId == '') {
					if (data.cat_hot) {
						sort_name = data.cat_hot.name
						sortList = data.cat_hot.good_list
						sort_index = ['hot', '', '']
						sort_desc = data.cat_hot.desc
					} else if (data.cat_discount) {
						sort_name = data.cat_discount.name
						sortList = data.cat_discount.good_list
						sort_index = ['discount', '', '']
						sort_desc = data.cat_discount.desc
					} else if (data.category_list.length > 0) {
						let sortItem = ''
						if (!data.category_list[0].son_list) {
							sortItem = data.category_list[0]
						} else {
							if (!data.category_list[0].son_list[0].son_list) {
								sortItem = data.category_list[0].son_list[0]
							} else {
								sortItem = data.category_list[0].son_list[0].son_list[0]
							}
						}
						sort_id = sortItem.sort_id
						sort_name = sortItem.sort_name
						sort_discount = sortItem.sort_discount
						// 请求对应分类的商品列表
						getGoodsList(sort_id)
					}
				} else {
					sort_id = _this.search_sortId
					let sortItem = ''
					outer: for (let i = 0; i < data.category_list.length; i++) {
						let one = data.category_list[i]
						if (one.sort_id == sort_id) {
							sort_index = [i, '', '']
							sortItem = one
							break outer
						} else if (one.son_list) {
							for (let j = 0; j < one.son_list.length; j++) {
								let two = one.son_list[j]
								if (two.sort_id == sort_id) {
									sort_index = [i, j, '']
									sortItem = two
									break outer
								} else if (two.son_list) {
									for (let k = 0; k < two.son_list.length; k++) {
										let three = two.son_list[k]
										if (three.sort_id == sort_id) {
											sort_index = [i, j, k]
											sortItem = three
											break outer
										}
									}
								}
							}
						}
					}
					sort_discount = sortItem.sort_discount
					sort_name = sortItem.sort_name
					// 请求对应分类的商品列表
					getGoodsList(sort_id)
				}

				sort_discount = sort_discount / 10
			}

			if (data.phone != '') {
				data.phone_list = data.phone.split(' ')
			}

			if (data.time_arr) {
				var time_width = 1

				for (var i = 0; i < data.time_arr.length; i++) {
					var arr = data.time_arr[i].time_show.split(',')

					if (arr.length == 3) {
						time_width = 3
						break
					} else if (arr.length == 2) {
						time_width = 2
					}
				}
			}

			_this.storeInfo = data
			_this.shopFrontColor = data.shop_fitment_front_color
			_this.shopBackgroundColor = data.shop_fitment_color
			_this.navIdList = _this.navIdList
			_this.contentTop = 0
			_this.sort_name = sort_name
			_this.sort_discount = sort_discount
			_this.sortList = sortList
			_this.sort_index = sort_index
			_this.sort_desc = sort_desc
			_this.time_width = time_width
			app.globalData.storeInfo = data

			if (_this.activityShare) {
				uni.navigateTo({
					url: `/pages/shop_new/goodsActivity/goodsActivity?store_id=${_this.store_id}&frontColor=${_this.shopFrontColor}&backgroundColor=${_this.shopBackgroundColor}`
				})
			}

			console.log('setNavigationBarColor 开始了')
			uni.setNavigationBarColor({
				frontColor: '#' + _this.shopFrontColor,
				backgroundColor: '#' + _this.shopBackgroundColor,
				complete: function(res) {
					console.log('setNavigationBarColor complete', res)
				}
			})

			if (data.store_notice) {
				_this.$nextTick(function() {
					initAnimation()
				})
			}

			if (data.is_booking == true || data.is_close == 1) {
				_this.showDailyTip = true

				if (data.is_booking == true) {
					var booking_time = ''
					booking_time = data.next_time.date ? data.next_time.date : ''
					booking_time = data.next_time.time ? booking_time + data.next_time.time : booking_time

					_this.booking_time = booking_time
				}
			}
			// 获取各种节点信息
			getHeight()

			// #ifdef MP-WEIXIN
			// 画海报
			drowPoster()
			// #endif

			// #ifdef H5
			_this.setWxShare()
			// #endif
		}
		_this.getDiscountList()
	})
}
// 判断商品是否已售罄、剩余几个
const isSoldOut = goodsItem => {
	goodsItem = goodsItem.map(item => {
		item.sold_out = false

		if (!item.has_spec && item.is_subsidiary_goods != 1 && ((!item.is_seckill_price && item.stock == 0) || (item.is_seckill_price && item.seckill_stock == 0))) {
			item.sold_out = true
		}

		if (_this.search_goodsId && item.product_id == _this.search_goodsId) {
			item.active = true
		}
		return item
	})
	return goodsItem
}

// 获取各种节点信息
const getHeight = () => {
	var p1 = getNodeInfo('#search', 'searchRect') // 搜索框

	var p2 = getNodeInfo('#tabHeader', 'tabHeaderRect') // tab头部

	var p3 = getNodeInfo('#topContent', 'topContentRect') // tab头部与商品列表中间的内容

	var p4 = getClassNode('.typeTitle', 'typeTitleArr') // 所有商品分类标题

	var p5 = ''
	if (_this.search_goodsId) {
		p5 = getNodeInfo('#id_' + _this.search_goodsId, 'searchGoods') // 搜索的商品
	}
	Promise.all([p1, p2, p3]).then(() => {
		Promise.all([p4, p5]).then(() => {
			console.log('节点信息 searchRect', _this.searchRect)
			console.log('节点信息 tabHeaderRect', _this.tabHeaderRect)
			console.log('节点信息 topContentRect', _this.topContentRect)
			console.log('节点信息 typeTitleArr', _this.typeTitleArr)
			console.log('节点信息 searchGoods', _this.searchGoods)
			// 50 是底部购物车的高度
			var searchRect = _this.searchRect
			var topContentRect = _this.topContentRect
			var tabHeaderRect = _this.tabHeaderRect
			var bottomCartH = 50
			var scrollHeight = 0

			scrollHeight = phoneInfo.windowHeight - searchRect.height - tabHeaderRect.height - bottomCartH
			var winHeight1 = phoneInfo.windowHeight - searchRect.height - tabHeaderRect.height + topContentRect.height
			console.log('222222222299999', phoneInfo, winHeight1)
			var scrollDistance = topContentRect.bottom - searchRect.height - tabHeaderRect.height
			var winHeight2 = scrollHeight + bottomCartH

			if (_this.topList == '') {
				_this.topList = _this.typeTitleArr.map(item => item.top - _this.typeTitleArr[0].top)
			}

			_this.pageIsScroll = true
			_this.scrollHeight = scrollHeight - 30 // 30为满减条
			_this.winHeight1 = winHeight1
			_this.winHeight2 = winHeight2
			_this.scrollDistance = scrollDistance
			if (_this.storeInfo.product_list) {
				var scrollY = _this.scrollY
				_this.storeInfo.product_list = _this.storeInfo.product_list.map((item, index) => {
					if (_this.search_sortId == '') {
						item.active = index == 0
					} else {
						if (item.cat_id == _this.search_sortId) {
							item.active = true
							item.product_list.map(i => {
								i.active = i.product_id == _this.search_goodsId
								return i
							})
						} else {
							item.active = false
						}

						scrollY = true
					}

					return item
				})

				_this.storeInfo = _this.storeInfo
				_this.scrollY = scrollY
			}

			console.log('search_goodsId', _this.search_goodsId)
			console.log('scrollDistance', scrollDistance)
			if (_this.search_goodsId) {
				var contentTop = _this.searchGoods.top - _this.typeTitleArr[0].top
				_this.scrollY = true
				_this.$nextTick(function() {
					_this.pageScrollTop = scrollDistance
					_this.contentTop = contentTop
					console.log('zyl contenttop3', _this.contentTop)
				})
			}
		})
	})
}
// 百度经纬度转腾讯经纬度
const baiduToTengxun = () => {
	var dataset = {
		type: 'baidu',
		name: _this.storeInfo.name,
		address: _this.storeInfo.adress,
		lng: _this.storeInfo.lng,
		lat: _this.storeInfo.lat
	}
	common.openMap(dataset)
}
// 请求商品列表
const getGoodsList = (id, update) => {
	// 避免重复点击造成的重复请求
	if (!id || (id == _this.sort_id && !update)) {
		return
	}

	var param = {
		store_id: _this.store_id,
		sort_id: id
	}
	if (update) {
		param.noTip = true
	}
	_this.$nextTick(function() {
		common.post('Shop_new&a=getGoodsBySortId', param, data => {
			if (data) {
				data.map(i => {
					i.active = i.product_id == _this.search_goodsId
					if ((i.is_seckill_price && i.seckill_stock == 0) || (!i.is_seckill_price && i.stock == 0)) {
						i.sold_out = true
					}
					return i
				})

				_this.sortList = data
				_this.sort_id = id
			} else {
				_this.sortList = []
				_this.sort_id = id
			}
		})
	})
}
// 请求评论列表
const getComment = () => {
	var param = {
		store_id: _this.store_id,
		tab: _this.tab,
		page: _this.pageIndex
	}
	common.post('Shop&a=ajax_reply', param, data => {
		if (data) {
			if (_this.pageIndex === 1) {
				_this.comment = data
			} else {
				// 分页数据未做处理
				_this.comment.list = _this.comment.list.concat(data.list)
			}

			if (_this.pageIndex < data.total) {
				_this.pageLoading = true
				_this.pageIndex = _this.pageIndex + 1
			} else {
				_this.pageLoading = false
			}
		}
	})
}
const setStoreInfoStorage = () => {
	if (_this.selectGoods.length > 0) {
		var storeInfo = {
			name: _this.storeInfo.name,
			store_id: _this.storeInfo.store_id,
			delivery: _this.storeInfo.delivery,
			delivery_price: _this.storeInfo.delivery_price,
			image: _this.storeInfo.image,
			is_close: _this.storeInfo.is_close
		}
		shop_common.setStorage('store' + _this.store_id, {
			selectGoods: _this.selectGoods,
			selectType: _this.selectType,
			goodsNumList: _this.goodsNumList,
			totalNum: _this.totalNum,
			selectAdd: _this.selectAdd,
			storeInfo: storeInfo
		})
		shop_common.getStorage('storeId_list').then(
			storeId_list => {
				var id = ''
				storeId_list = storeId_list.filter(item => item != _this.store_id)
				storeId_list.unshift(_this.store_id)

				if (storeId_list.length > 20) {
					id = storeId_list[20]
					wx.removeStorage({
						key: 'store' + id
					})
					storeId_list = storeId_list.slice(0, 20)
				}

				shop_common.setStorage('storeId_list', storeId_list)
			},
			() => {
				shop_common.setStorage('storeId_list', [_this.store_id])
			}
		)
	}
}
const getCoupon = id => {
	common.post(
		'Shop&a=had_pull',
		{
			coupon_id: id
		},
		data => {
			if (data) {
				common.getTxtKey('领取成功！').then(
					key => {
						wx.showToast({
							title: key
						})
					},
					() => {}
				)
			}
		},
		_this,
		() => {
			common.getTxtKey('已经领取过了~').then(
				key => {
					wx.showToast({
						title: key,
						icon: 'none'
					})
				},
				() => {}
			)
		}
	)
}
const barcodeSearch = barcode => {
	console.log('2222222222222', barcode)

	if (barcode.indexOf('http://') === 0 || barcode.indexOf('https://') === 0) {
		if (barcode.indexOf('Shop_new&a=ajax_goods') === 0) {
			common.post(
				'Shop_new&a=ajax_goods',
				{
					goods_id: data.goods_id_real
				},
				goodsInfo => {
					if (goodsInfo.store_id == _this.store_id) {
						wx.navigateTo({
							url: `/pages/shop_new/goodsDetail/goodsDetail?store_id=${_this.store_id}&product_id=${data.goods_id_real}`
						})
					} else {
						common.getTxtKey('该商品不属于此店铺').then(
							key => {
								wx.showToast({
									title: key,
									icon: 'none',
									duration: 2000
								})
							},
							() => {}
						)
					}
				}
			)
		} else {
			wx.showToast({
				title: common.changeTxt('店铺内未搜索到该商品'),
				icon: 'none',
				duration: 2000
			})
		}
	} else {
		var param = {
			barcode: barcode,
			store_id: _this.store_id,
			refresh: 1
		}
		console.log('33333333', param)
		common.post('Shop_new&a=shop_barcode_search', param, data => {
			console.log('44444444', data)

			_this.refresh = _this.refresh + 1

			if (data.goods_id_real) {
				wx.navigateTo({
					url: `/pages/shop_new/goodsDetail/goodsDetail?store_id=${_this.store_id}&product_id=${data.goods_id_real}`
				})
			} else {
				wx.showToast({
					title: common.changeTxt('店铺内未搜索到该商品'),
					icon: 'none',
					duration: 2000
				})
			}
		})
	}
}
const drowPoster = () => {
	var shop = _this.storeInfo
	var ctx = wx.createCanvasContext('pubShare')
	wx.getSystemInfo({
		success: system => {
			console.log('getSystemInfo ok')
			wx.getImageInfo({
				src: shop.image,
				success: logo => {
					console.log('getImageInfo ok')
					logo.height = (logo.height / logo.width) * 100
					var width = system.windowWidth
					var height = logo.height + 310

					_this.width = width
					_this.height = height
					// 绘制背景

					ctx.fillStyle = 'white'
					ctx.fillRect(0, 0, width, height) // 边框

					ctx.beginPath()
					ctx.lineWidth = 0.2
					ctx.strokeStyle = '#666666'
					ctx.strokeRect(25, 60, width - 50, height - 80)
					ctx.closePath() // 店铺图片

					ctx.drawImage(logo.path, width / 2 - 50, 20, 100, logo.height) // 店铺名称

					ctx.font = 'bold 20px 微软雅黑'
					var max_width = width - 100
					var metrics = ctx.measureText(shop.name)

					if (metrics.width > max_width) {
						var num = Math.ceil(max_width / 20)
						shop.name = shop.name.slice(0, num) + '...'
					}

					ctx.fillStyle = '#333333'
					ctx.setTextAlign('center')
					ctx.fillText(shop.name, width / 2, logo.height + 55) // 星星

					for (let i = 0; i < 5; i++) {
						if (shop.star - i > 1) {
							ctx.drawImage('../../../static/images/sn_total.png', width / 2 + 12 * i - 65, logo.height + 70, 10, 9.5)
						} else if (shop.star - i > 0) {
							ctx.drawImage('../../../static/images/sn_half.png', width / 2 + 12 * i - 65, logo.height + 70, 10, 9.5)
						} else {
							ctx.drawImage('../../../static/images/sn_empty.png', width / 2 + 12 * i - 65, logo.height + 70, 10, 9.5)
						}
					}

					ctx.font = 'normal 12px 微软雅黑'
					ctx.fillStyle = '#666666'
					ctx.setTextAlign('left')
					ctx.fillText(shop.star + '  ' + common.changeTxt('已售') + shop.month_sale_count, width / 2, logo.height + 80)
					ctx.font = 'bold 14px 微软雅黑'
					ctx.fillStyle = '#000000'
					ctx.setTextAlign('center')
					ctx.fillText('一 ' + common.changeTxt('店铺优惠') + ' 一', width / 2, logo.height + 120)
					ctx.font = 'normal 14px 微软雅黑'
					ctx.setTextAlign('left')
					ctx.strokeStyle = 'red'
					ctx.fillStyle = 'red'
					var coupon = []
					var total = 0

					for (var i = 0; i < shop.coupon_list.length; i++) {
						if (i == 0) {
							total = ctx.measureText(shop.coupon_list[i].value).width + 10
						} else {
							total = total + ctx.measureText(shop.coupon_list[i].value).width + 15
						}

						if (total < max_width || i == 0) {
							coupon[i] = ctx.measureText(shop.coupon_list[i].value).width
						} else {
							total = total - (ctx.measureText(shop.coupon_list[i].value).width + 15)
							break
						}
					}

					var x = (max_width - total) / 2 + 50

					for (var i = 0; i < coupon.length; i++) {
						ctx.fillText(shop.coupon_list[i].value, x, logo.height + 150)
						ctx.strokeRect(x - 5, logo.height + 135, coupon[i] + 10, 20)
						x = x + coupon[i] + 15
					} // 虚线

					ctx.beginPath()
					ctx.strokeStyle = '#666666'
					ctx.setLineDash([10, 11], 1)
					ctx.lineWidth = 0.2
					ctx.moveTo(25, logo.height + 180)
					ctx.lineTo(width - 25, logo.height + 180)
					ctx.stroke()
					ctx.closePath() // 二维码

					wx.getImageInfo({
						src: shop.wxapp_qrcode,
						success: qcode => {
							console.log('getImageInfo wxapp_qrcode success', qcode.path)

							ctx.drawImage(qcode.path, width / 2 - 115, logo.height + 195, 80, 80)
							ctx.font = 'bold 15px 微软雅黑'
							ctx.fillStyle = '#000000'
							ctx.fillText(common.changeTxt('长按识别，进店购物'), width / 2 - 25, logo.height + 240)
							ctx.draw(false, () => {
								_this.posterUrl = true
							})

							_this.posterUrl = true
						},
						fail: result => {
							console.log('getImageInfo wxapp_qrcode fail', result)
							_this.posterUrl = false
						}
					})
				},
				fail: result => {
					console.log('getImageInfo fail', result)

					_this.posterUrl = false
				},
				complete: () => {
					_this.posterComplete = true
				}
			})
		},
		fail: result => {
			console.log('getSystem Fail', result)
		}
	})
}
const saveImg = () => {
	if (_this.posterUrl === true) {
		wx.canvasToTempFilePath({
			canvasId: 'pubShare',
			fileType: 'jpg',
			success: res => {
				wx.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,

					success(res) {
						wx.showToast({
							title: common.changeTxt('保存成功!')
						})
					},

					fail: () => {
						wx.getSetting({
							success: res => {
								if (res.authSetting['scope.writePhotosAlbum'] == false) {
									_this.canSave = false
								}
							}
						})
					}
				})
			}
		})
	}
}
//获取id节点信息
const getNodeInfo = (id, name) => {
	return new Promise((resolve, reject) => {
		var timer = setInterval(function() {
			wx.createSelectorQuery()
				.select(id)
				.fields(
					{
						dataset: true,
						size: true,
						rect: true
					},
					function(res) {
						if (res) {
							clearInterval(timer)
							_this[name] = res
							resolve(res)
						}
					}
				)
				.exec()
		}, 500)
	})
}
// class节点
const getClassNode = (className, name) => {
	return new Promise((resolve, reject) => {
		setTimeout(function() {
			uni.createSelectorQuery()
				.selectAll(className)
				.fields(
					{
						dataset: true,
						size: true,
						rect: true
					},
					function(res) {
						console.log('22222节点信息', name, res)
						if (res) {
							_this[name] = res
							resolve(true)
						}
					}
				)
				.exec()
		}, 500)
	})
}
// 开启公告滚动
const initAnimation = () => {
	wx.createSelectorQuery()
		.select('#marquee_box')
		.boundingClientRect(function(box) {
			_this.boxWidth = box ? box.width : 220
			wx.createSelectorQuery()
				.select('.every')
				.boundingClientRect(function(rect) {
					if (!rect || (rect && box && rect.width < box.width)) {
						return
					}

					var length = rect.width
					_this.length = rect.width

					_this.hidden = 'hidden'

					run2()
				})
				.exec()
		})
		.exec()
}
const run2 = () => {
	roll_interval = setInterval(function() {
		if (-_this.marqueeDistance2 < _this.length) {
			_this.marqueeDistance2 = _this.marqueeDistance2 - _this.marqueePace
		} else {
			clearInterval(roll_interval)

			_this.marqueeDistance2 = _this.boxWidth

			run2()
		}
	}, 30)
}
</script>

<style lang="scss">
@import './takeout-sub.scss';
</style>
